import { defineStore } from 'pinia'
import request from '@/utils/request'
import { apiRes, catagoryItem, TopCatagory, SubCategory } from '@/types/data'
import { topCatagory } from '../constants'

const defaultCategory = topCatagory.map((item) => {
  return {
    name: item,
  }
})

export default defineStore('catagory', {
  state: () => ({
    catagoryList: defaultCategory as catagoryItem[],
    topCategory: {} as TopCatagory,
    subCategory: {} as SubCategory,
  }),
  actions: {
    async getAllCatagory() {
      const res = await request.get<apiRes<catagoryItem[]>>(
        '/home/category/head'
      )
      // 给list添加一个open属性，用于控制二级分类的显示与隐藏
      res.data.result.forEach((item) => {
        item.open = false
      })
      this.catagoryList = res.data.result
    },
    show(id: string) {
      const catagory = this.catagoryList.find((item) => item.id === id)!
      catagory.open = true
    },
    hide(id: string) {
      const catagory = this.catagoryList.find((item) => item.id === id)!
      catagory.open = false
    },
    async getTopCategory(id: string) {
      const res = await request.get<apiRes<TopCatagory>>('/category', {
        params: {
          id,
        },
      })
      this.topCategory = res.data.result
    },
    async getSubFilter(id: string) {
      const res = await request.get<apiRes<SubCategory>>(
        '/category/sub/filter',
        {
          params: {
            id,
          },
        }
      )
      this.subCategory = res.data.result
    },
  },
})
